package com.jjty.dataGenerator.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class LocationUtil {
    // 替换为你自己的高德地图 API 密钥
    private static final String API_KEY = "47235ed632b28a30b36409ddab49d59a";
    // 高德地图地理编码 API 地址
    private static final String GEOCODING_URL = "https://restapi.amap.com/v3/geocode/regeo"; 

    public static String getLocationAddress(String lon, String lat) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 拼接请求参数
            String url = GEOCODING_URL + "?key=" + API_KEY + "&location=" + lon + "," + lat;
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity());
                // 解析返回结果获取地址信息（这里简单示例，实际可能更复杂）
                // 假设返回 JSON 格式，可使用 JSON 解析库如 Jackson、Gson 等进一步处理
                int addressStartIndex = result.indexOf("\"formatted_address\":\"") + "\"formatted_address\":\"".length();
                int addressEndIndex = result.indexOf("\"", addressStartIndex);
                return result.substring(addressStartIndex, addressEndIndex);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

//    public static void main(String[] args) {
//        String lon = "117.4327146";
//        String lat = "31.1609193";
//        String address = getLocationAddress(lon, lat);
//        System.out.println(address);
//    }
}